let arguments = process.argv.splice(2);
let pid = 0;
let serverName = "pro";
if (arguments.length) {
  serverName = arguments[0];
}

require("./time-log");
const pidusage = require("pidusage");
const alert = require("./alert");
const processHelper = require("./process-helper");
const util = require("./util");

let isFirst = true;
let isWarning = false;
let warnStartTime = new Date().valueOf();

function getCPU() {
  return new Promise((resolve, reject) => {
    pidusage(pid, function (err, stats) {
      if (err) {
        reject(err);
        return console.log(err);
      }
      let cpu = parseInt(stats.cpu);
      let memory = parseInt(stats.memory / 1048576);
      resolve({ cpu, memory });
    });
  });
}
async function main() {
  try {
    // let pid2 = await processHelper.findPid("taoxin-admin");
    // if (pid2) {
    //   pid = pid2;
    // }
    // if (!pid) {
    //   return console.log("pid 未找到");
    // }
    const { cpu, memory } = await processHelper.getCPU();
    if (isFirst) {
      isFirst = false;
      alert.send(
        `服务器【${serverName}】监控启动成功，CPU占用率：${cpu}%，内存：${memory}%`
      );
      return;
    }
    console.log("cpu:", util.tostr(cpu) + "%  memory:", memory + "%");
    if (cpu > 70) {
      if (isWarning) return;
      isWarning = true;
      warnStartTime = new Date().valueOf();
      alert.send(
        `服务器【${serverName}】CPU占用率过高：${cpu}%，内存：${memory}%`
      );
      //关闭程序
      let result = await processHelper.myexec("pm2 stop web-admin");
      console.log("关闭程序，结果:");
      console.log(result);
    } else {
      if (isWarning && cpu < 50) {
        isWarning = false;
        let warnEnd = parseInt((new Date().valueOf() - warnStartTime) / 1000);
        alert.send(
          `服务器【${serverName}】CPU占用率过高已恢复：${cpu}%，内存：${memory}%，故障时间：${warnEnd}s`
        );
        //恢复程序
        console.log("CPU占用率过高已恢复,等待10秒后恢复");
        await util.sleep(10); //等待5秒再启动
        let result = await processHelper.myexec("pm2 start web-admin");
        console.log("打开程序，结果:");
        console.log(result);
      }
    }
  } catch (e) {
    console.log(e);
  }
}
setInterval(function () {
  main();
}, 3000);
